import { reactive, ref } from 'vue'
import { NewReceiptParam } from '@/api/chunfeng/finance/receipt/interfaces'
import moment from 'moment'
import { useForm } from 'ant-design-vue/es/form'
import { useHttpRequest } from '@/api/chunfeng/apiRequest'
import { useReceiptApi } from '@/api/chunfeng/finance/receipt'

export const useReceiptAddFunctions = () => {
  const newReceiptParam = reactive<NewReceiptParam>({
    customerId: '',
    amount: 1,
    occurredAt: moment().format('yyyy-MM-DD'),
  })
  const rules = reactive({
    customerId: [
      {
        required: true,
        message: '请选择客户名称',
      },
    ],
    amount: [
      {
        required: true,
        message: '请输入金额',
      },
    ],
    occurredAt: [
      {
        required: true,
        message: '请选择发生日期',
      },
    ],
  })

  const { validateInfos, resetFields, validate } = useForm(newReceiptParam, rules)
  const { executeCommandRequest } = useHttpRequest()
  const { newReceipt } = useReceiptApi()
  const csRef = ref()

  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
  }

  function addReceipt() {
    validate().then((data: NewReceiptParam) => {
      executeCommandRequest(newReceipt(newReceiptParam), {
        message: '新增收款成功',
        callback: () => {
          resetFields()
          csRef.value.reset()
        },
      })
    })
  }

  function reset() {
    resetFields()
  }

  function customerSelected(customerId: string) {
    newReceiptParam.customerId = customerId
  }

  return {
    newReceiptParam,
    rules,
    validateInfos,
    addReceipt,
    reset,
    customerSelected,
    csRef,
    layout,
  }
}
